<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <title th:text="#{forgot.password.title}"></title>

    <script th:inline="javascript">

        // 生成随机验证码
        function generateCaptcha() {
            const captchaChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
            let captcha = '';
            for (let i = 0; i < 4; i++) {
                captcha += captchaChars.charAt(Math.floor(Math.random() * captchaChars.length));
            }
            return captcha;
        }

        // 绘制验证码
        function drawCaptcha() {
            const captcha = generateCaptcha();
            const captchaElement = document.getElementById('captcha-image');
            captchaElement.innerHTML = captcha;
            captchaElement.dataset.captcha = captcha;

            // 添加干扰效果
            captchaElement.style.background = `#${Math.floor(Math.random()*16777215).toString(16)}`;
            captchaElement.style.color = `#${Math.floor(Math.random()*16777215).toString(16)}`;
        }

        // 倒计时函数
        function countDown() {
            let seconds = 60;
            const codeBtn = document.getElementById('get-code-btn-id');
            const originalText = codeBtn.textContent;

            const timer = setInterval(function() {
                codeBtn.textContent = `${seconds}s`;
                seconds--;

                if (seconds < 0) {
                    clearInterval(timer);
                    codeBtn.textContent = originalText;
                    codeBtn.disabled = false;
                    codeBtn.style.backgroundColor = '#5bc0de';
                    codeBtn.style.cursor = 'pointer';
                }
            }, 1000);
        }

        $(function () {
            // 初始化验证码
            drawCaptcha();

            // 点击刷新验证码
            document.getElementById('captcha-image').addEventListener('click', drawCaptcha);

            // 获取验证码按钮点击事件
            $('#get-code-btn-id').click(function() {
                const username = document.getElementById('username-id').value;
                if (!username || username.trim() === '') {
                    alert('请输入用户名或邮箱');
                    return;
                }

                // 验证图形验证码
                const userCaptcha = document.getElementById('captcha-input').value;
                const correctCaptcha = document.getElementById('captcha-image').dataset.captcha;
                if (!userCaptcha || userCaptcha.trim() === '') {
                    alert('请输入验证码');
                    return;
                }
                if (userCaptcha.toUpperCase() !== correctCaptcha.toUpperCase()) {
                    alert('验证码错误，请重新输入');
                    drawCaptcha();
                    return;
                }

                // 发送验证码到后端
                $.ajax({
                    url: '/login/sendVerifyCode',
                    type: 'POST',
                    data: {username: username},
                    success: function(response) {
                        if (response.success) {
                            alert('验证码发送成功，请查收');
                            // 禁用按钮并开始倒计时
                            $('#get-code-btn-id').text('60s');
                            $('#get-code-btn-id').prop("disabled", true);
                            $('#get-code-btn-id').css({"background-color": "#ccc", "cursor": "not-allowed"});
                            countDown();
                        } else {
                            alert(response.message);
                        }
                    },
                    error: function() {
                        alert('发送验证码失败，请重试');
                    }
                });
            });

            // 重置密码按钮点击事件
            $('#reset-password-btn-id').click(function() {
                // 验证表单
                const username = document.getElementById('username-id').value;
                const verifyCode = document.getElementById('verify-code-id').value;
                const newPassword = document.getElementById('new-password-id').value;
                const confirmPassword = document.getElementById('confirm-password-id').value;

                if (!username || username.trim() === '') {
                    alert('请输入用户名或邮箱');
                    return;
                }

                if (!verifyCode || verifyCode.trim() === '') {
                    alert('请输入验证码');
                    return;
                }

                if (!newPassword || newPassword.length < 6) {
                    alert('密码长度不能少于6位');
                    return;
                }

                if (newPassword !== confirmPassword) {
                    alert('两次输入的密码不一致');
                    return;
                }

                // 提交重置密码请求到后端
                $.ajax({
                    url: '/login/resetPassword',
                    type: 'POST',
                    data: {
                        verifyCode: verifyCode,
                        newPassword: newPassword
                    },
                    success: function(response) {
                        if (response.success) {
                            alert('密码重置成功，请登录');
                            window.location.href = '/login/login';
                        } else {
                            alert(response.message);
                        }
                    },
                    error: function() {
                        alert('重置密码失败，请重试');
                    }
                });
            });
        });
    </script>

    <style>
        body {
            display: flex;
            flex-direction: column;
        }

        body > header {
            display: flex;
            width: 100%;
            justify-content: space-between;
            padding: 10px;
            align-items: center;
            height: 100px;
        }

        body > header > img {
            height: 80px;
        }

        body > header > nav {
            width: 150px;
            display: flex;
            justify-content: space-between;
            padding-right: 20px;
        }

        body > article {
            flex-grow: 1;
            background-color: #d4efec;
            width: 100%;
            display: flex;
            align-items: center;
        }

        body > article > section {
            flex-grow: 1;
            display: flex;
        }

        body > article > form {
            flex-basis: 300px;
            margin-right: 30px;
        }

        #reset-password-btn-id {
            width: 100%;
        }

        #get-code-btn-id {
            width: 120px;
        }
        #forgotPassword-btn-id{
            width: 100%;
            background-color: #4cae4c;
        }

    </style>
</head>
<body>
<header>
    <img th:if="${session.lang} eq 'en'" th:src="@{/assets/images/logo_en.png}">
    <img th:unless="${session.lang} eq 'en'" th:src="@{/assets/images/logo_zh.png}">

    <nav>
        <a th:href="@{/login/login(lang=en)}" th:text="#{login.english}"></a>
        <a th:href="@{/login/login(lang=zh)}" th:text="#{login.chinese}"></a>
    </nav>
</header>
<article>
    <section>
        <img th:src="@{/assets/images/pic.png}">
    </section>

    <form id="forgot-password-form-id" method="post">
        <div class="form-group">
            <span th:text="#{login.user.name.or.email}"></span>
            <input id="username-id" class="form-control" name="username" type="text"
                   th:placeholder="#{login.user.name.or.email.plch}"
                   th:title="#{login.user.name.or.email.plch}">
        </div>

        <div class="form-group">
            <span th:text="#{login.captcha}"></span>
            <div style="display: flex; gap: 10px;">
                <input class="form-control" name="captcha" id="captcha-input"
                       th:placeholder="#{login.captcha.plch}"
                       th:title="#{login.captcha.plch}"
                       pattern="^.{4,}$">
                <div id="captcha-image" style="width: 120px; height: 40px; background-color: #f0f0f0; display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: bold; letter-spacing: 5px; cursor: pointer;"></div>
            </div>
        </div>

        <div class="form-group">
            <span th:text="#{verify.code}"></span>
            <div style="display: flex; gap: 10px;">
                <input class="form-control" name="verifyCode" id="verify-code-id"
                       th:placeholder="#{verify.code.plch}"
                       th:title="#{verify.code.plch}">
                <button type="button" id="get-code-btn-id" class="btn btn-info"
                        th:text="#{get.verify.code}"></button>
            </div>
        </div>

        <div class="form-group">
            <span th:text="#{new.password}"></span>
            <input id="new-password-id" class="form-control" name="newPassword" type="password"
                   th:placeholder="#{new.password.plch}"
                   th:title="#{new.password.plch}"
                   pattern="^.{6,}$">
        </div>

        <div class="form-group">
            <span th:text="#{confirm.password}"></span>
            <input id="confirm-password-id" class="form-control" name="confirmPassword" type="password"
                   th:placeholder="#{confirm.password.plch}"
                   th:title="#{confirm.password.plch}"
                   pattern="^.{6,}$">
        </div>

        <div style="display: flex; gap: 10px; margin-top: 10px;">
            <button type="button" id="reset-password-btn-id" class="btn btn-success btn-group-lg flex-fill"
                    th:text="#{reset.password}"></button>
        </div>

        <div style="margin-top: 10px; text-align: center;">
            <a th:href="@{/login/login}" th:text="#{back.to.login}"></a>
        </div>
    </form>
</article>
</body>
</html>